package com.sk.sourcecircle.activity.home.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.home.activity.AblumDetailsActivity;
import com.sk.sourcecircle.activity.home.activity.GroupDetailsActivity;
import com.sk.sourcecircle.activity.login.LoginActivity;
import com.sk.sourcecircle.adapter.AblumListAdapter;
import com.sk.sourcecircle.base.BaseFragment;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.callback.MyCallBack;
import com.sk.sourcecircle.dialog.CommentDialogFragment;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.AlbumListBean;
import com.sk.sourcecircle.entity.AlbumaBean;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.HttpAddress;
import com.sk.sourcecircle.utils.MD5;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.view.EasyLoadingMoreView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.Unbinder;

import static com.sk.sourcecircle.activity.home.activity.GroupDetailsActivity.Group;

/**
 * Created by sk on 2017/12/13.
 */

public class GroupShareFragment extends BaseFragment implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener, HandleDataCallBack, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.data_ryc)
    RecyclerView dataRyc;
    Unbinder unbinder;
    private int id;

    private int page = 1;
    private AblumListAdapter adapter;
    private List<AlbumaBean> allDataList = new ArrayList<>();
    private boolean isLoadMore = false;
    private LoadingDialog loadingDialog;
    private int seletId;
    private int pos;
    private String comment = "";

    @Override
    protected int getContentView() {
        return R.layout.layout_recycler;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        dataRyc.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new AblumListAdapter(R.layout.item_album, allDataList);
        dataRyc.setAdapter(adapter);
        EasyLoadingMoreView loadMoreView = new EasyLoadingMoreView();
        adapter.setLoadMoreView(loadMoreView);
        View emptyView = getLayoutInflater().inflate(R.layout.empty_view, null);
        adapter.setEmptyView(emptyView);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this, dataRyc);

        if (getActivity() instanceof GroupDetailsActivity) {
            id = ((GroupDetailsActivity) getActivity()).getGroupId();
            getAlbum(page);
        }
    }

    public void getAlbum(int page) {
        String path = HttpAddress.TestIp + HttpAddress.GroupAblum;
        RequestParams requestParams = new RequestParams(path);
        long timeStamp = System.currentTimeMillis()/1000;
        requestParams.addBodyParameter("timestamp", String.valueOf(timeStamp));
        requestParams.addBodyParameter("sign", MD5.md5(timeStamp + "_yuanquan"));
        requestParams.addBodyParameter("token", MyUtils.getToken(mContext));
        requestParams.addBodyParameter("page", String.valueOf(page));
        requestParams.addBodyParameter("community_id", String.valueOf(id));
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.v("getAlbum", result);
                AlbumListBean albumListBean = JSON.parseObject(result, AlbumListBean.class);
                List<AlbumaBean> dataBeanList = albumListBean.getData();
                allDataList.addAll(dataBeanList);
                if (allDataList.size() < 10) {
                    adapter.setEnableLoadMore(false);
                } else {
                    adapter.setEnableLoadMore(true);
                }
                if (isLoadMore) {
                    adapter.loadMoreComplete();
                    if (dataBeanList.size() == 0) {
                        adapter.loadMoreEnd();
                    }
                    isLoadMore = false;
                }
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.v("getAlbum", ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        pos = position;
        switch (view.getId()) {
            case R.id.comment:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent, Group);
                    return;
                }
                seletId = allDataList.get(position).getAlbum_id();
                CommentDialogFragment commentDialogFragment = new CommentDialogFragment();
                commentDialogFragment.setCallBack(GroupShareFragment.this);
                if (allDataList.get(position).getDetail().getIs_favorite() == 1) {
                    commentDialogFragment.setCollect(true);
                } else {
                    commentDialogFragment.setCollect(false);
                }
                commentDialogFragment.show(getActivity().getSupportFragmentManager(), "comment");
                break;
            case R.id.add_praise:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent, Group);
                    return;
                }
                loadingDialog.show();
                seletId = allDataList.get(position).getAlbum_id();
                AppApi.praiseAlbum(allDataList.get(position).getAlbum_id(), GroupShareFragment.this, 2, getActivity());
                break;
            case R.id.cancel_praise:
                break;
            case R.id.add_care:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent, Group);
                    return;
                }
                loadingDialog.show();
                AppApi.addFriend(allDataList.get(position).getUser_id(), GroupShareFragment.this, 4, getActivity());
                break;
            case R.id.cancel_care:
                break;
            case R.id.more:
                allDataList.get(position).setExpand(true);
                adapter.notifyItemChanged(position);
                break;
            case R.id.tv_delete:
                final int id = allDataList.get(position).getAlbum_id();
                TipDialogFragment tipDialogFragment = new TipDialogFragment();
                tipDialogFragment.setMyCallBack(new MyCallBack() {
                    @Override
                    public void releaseAlbum() {

                    }

                    @Override
                    public void joinGroup() {

                    }

                    @Override
                    public void takePhoto() {

                    }

                    @Override
                    public void choosePhoto() {

                    }

                    @Override
                    public void sure() {
                        loadingDialog.show();
                        AppApi.deleteAblumn(id, GroupShareFragment.this, 16, getActivity());
                    }

                    @Override
                    public void cancelOder(String string) {

                    }

                    @Override
                    public void chooseGroup(String id) {

                    }

                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void sendText(String comment) {

                    }
                });
                tipDialogFragment.setContent("确认删除该相册？");
                tipDialogFragment.show(getChildFragmentManager(), "delete");
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        isLoadMore = true;
        page++;
        getAlbum(page);
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 1:
                SnackUtils.show(mRootView, "评论发布成功！");
                AlbumaBean.DetailBean.ReplyBean replyBean = new AlbumaBean.DetailBean.ReplyBean();
                replyBean.setContent(comment);
                replyBean.setType("reply");
                replyBean.setNickname(MyUtils.getName(mContext));
                allDataList.get(pos).getDetail().getReply().add(replyBean);
                adapter.notifyItemChanged(pos);
                break;
            case 6:
                SnackUtils.show(mRootView, "相册收藏成功！");
                allDataList.get(pos).getDetail().setIs_favorite(1);
                adapter.notifyItemChanged(pos);
                break;
            case 2:
                SnackUtils.show(mRootView, "点赞成功！");
                AlbumaBean.DetailBean.ReplyBean praiseBean = new AlbumaBean.DetailBean.ReplyBean();
                praiseBean.setType("dig");
                praiseBean.setNickname(MyUtils.getName(mContext));
                allDataList.get(pos).getDetail().getReply().add(praiseBean);
                allDataList.get(pos).getDetail().setIs_dig(1);
                adapter.notifyItemChanged(pos);
                break;
            case 4:
                SnackUtils.show(mRootView, "请求发送成功，请等待回复！");
                break;
            case 16:
                SnackUtils.show(mRootView, "相册删除成功！");
                allDataList.remove(pos);
                adapter.notifyItemRemoved(pos);
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();

    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();

    }

    @Override
    public void sendText(String comment) {
        super.sendText(comment);
        loadingDialog.show();
        this.comment = comment;
        AppApi.commentAlbum(seletId, comment, GroupShareFragment.this, 1, getActivity());
    }

    @Override
    public void sure() {
        super.sure();
        loadingDialog.show();
        AppApi.collectAlbum(seletId, GroupShareFragment.this, 6, getActivity());
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
            Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(mContext, LoginActivity.class);
            startActivityForResult(intent, Group);
            return;
        }
        Intent intent = new Intent(mContext, AblumDetailsActivity.class);
        intent.putExtra("data", allDataList.get(position));
        startActivity(intent);
    }

    public void doRefresh() {
        page = 1;
        allDataList.clear();
        getAlbum(page);
    }
}
